/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ntb.controllers;

import com.ntb.common.MailUtil;
import com.ntb.common.StringUtil;
import com.ntb.controllers.forms.LoginForm;
import com.ntb.entities.Users;
import com.ntb.models.UsersDAO;
import com.ntb.models.impl.UsersDAOImpl;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Thinh Hung
 */
public class ForgotPasswordAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) {
        LoginForm loginForm = (LoginForm) form;

        String action = loginForm.getAction();

        ActionForward forward = mapping.getInputForward();

        if (("forgot").equalsIgnoreCase(action)) {
            UsersDAO usersDAO = new UsersDAOImpl();
            String username = "";
            try {
                username = loginForm.getUsername().trim().toLowerCase();
            } catch (NullPointerException e) {
            }

            Users user = usersDAO.getUser(username);
            if (user != null) {
                String baseUrl = request.getRequestURL().toString().replaceFirst(request.getRequestURI(), request.getContextPath()) + "/";
                StringUtil stringUtil = new StringUtil();
                MailUtil mailUtil = new MailUtil();

                String newPass = stringUtil.generateRandomString();
                String forgotCode = stringUtil.generateRandomString();
                String title = "You requested a new NTB password.";
                String content = "Hi, " + user.getFullName() +
                        "<br/><br/>You recently asked to reset your NTB password." +
                        "<br/><br/>Your username: " + user.getUserName() +
                        "<br/>Your new password: " + newPass +
                        "<br/><br/><a href=\"" + baseUrl + "getNewPassword.do?user=" + user.getUserID() + "&secure=" + forgotCode + "\">" +
                        "Click here to change your password.</a>" +
                        "<br/><br/>Best Regards," +
                        "<br/>NTB Team<br/>";
                usersDAO.updateForgotPassword(stringUtil.generateMD5(newPass), stringUtil.generateMD5(forgotCode), user.getUserID());
                
                mailUtil.sendMail(title, content, user.getEmail());
                request.setAttribute("successMessage", title);
            } else {
                request.setAttribute("errorMessage", "No account found with that username.");
            }
        }
        return forward;
    }
}
